package com.jiukuaidao.zhulin.module.order;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jiukuaidao.library.base.BaseActivity;
import com.jiukuaidao.library.base.BaseHolder;
import com.jiukuaidao.library.base.BaseRecyclerViewAdapter;
import com.jiukuaidao.library.common.dialog.CommDialog;
import com.jiukuaidao.library.common.dialog.ICallBack;
import com.jiukuaidao.library.util.DBUtils;
import com.jiukuaidao.library.util.ToastUtil;
import com.jiukuaidao.library.widget.recyclerview.XRecyclerView;
import com.jiukuaidao.zhulin.R;
import com.jiukuaidao.zhulin.data.TaskProvider;
import com.jiukuaidao.zhulin.entity.ApiConfirmOrderInfo;
import com.jiukuaidao.zhulin.entity.ApiHistoryAddressInfo;
import com.jiukuaidao.zhulin.entity.ApiHistoryAddressInfo.AddressInfo;
import com.jiukuaidao.zhulin.entity.ApiShoppingCartInfo;
import com.jiukuaidao.zhulin.entity.DBShoppingCartInfo;
import com.jiukuaidao.zhulin.entity.EventShoppingCartInfo;
import com.jiukuaidao.zhulin.module.CommContract;
import com.jiukuaidao.zhulin.module.CommPresenter;
import com.jiukuaidao.zhulin.module.order.contract.ConfirmOrderContract;
import com.jiukuaidao.zhulin.module.order.presenter.ConfirmOrderPresenter;
import com.jiukuaidao.zhulin.module.pay.wechat.WXPayContract;
import com.jiukuaidao.zhulin.module.pay.wechat.WXPayPresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Author : PaiTaSuo
 * Date : 2016/6/6
 * Description :
 */
public class ConfirmOrderActivity extends BaseActivity<ConfirmOrderContract.Presenter> implements CommContract.ShoppingCartNetView, ConfirmOrderContract.View, WXPayContract.View, View.OnClickListener {
    @BindView(R.id.titile_text)
    TextView mTitleText;
    @BindView(R.id.titile_left_imageview)
    ImageView mLeftImg;
    @BindView(R.id.rl_onlinepay)
    RelativeLayout mRlOnlinePay;
    @BindView(R.id.rl_cashpay)
    RelativeLayout mRlCashPay;
    @BindView(R.id.rl_cardpay)
    RelativeLayout mRlCardPay;
    @BindView(R.id.rg_onlinepay)
    RadioGroup mRgOnline;
    @BindView(R.id.rg_cashpay)
    RadioGroup mRgCash;
    @BindView(R.id.rg_cardpay)
    RadioGroup mRgCard;
    @BindView(R.id.rb_onlinepay)
    RadioButton mRbOnline;
    @BindView(R.id.rb_cashpay)
    RadioButton mRbCash;
    @BindView(R.id.rb_cardpay)
    RadioButton mRbCard;
    @BindView(R.id.order_recycle)
    XRecyclerView mProRecycle;
    @BindView(R.id.total_price)
    TextView mTotalPrice;
    @BindView(R.id.total_count)
    TextView mTotalCount;
    @BindView(R.id.order_deliver)
    TextView mOrderDeliver;
    @BindView(R.id.tv_confirm_order)
    TextView mConfirmOrder;
    private BaseRecyclerViewAdapter mBaseAdapter;
    // 以下信息为用于提交信息
    private int mCheckedPayWay = 1;// 支付方式 1：现金、2：刷卡、3：微信、4：财付通、5；支付宝
    private CommPresenter mCommPresenter;
    private List<EventShoppingCartInfo> mShoppingCartInfo;
    private AddressInfo mAddressInfo;
    private WXPayPresenter mWXPayPresenter;
    private String mInvoice;  // 发票抬头
    private String mRemark;   // 备注
    private String mOrderNo;  //订单
    private List<String> mIgnoreList;


    @Override
    protected View getTargetView() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_confirm_order;
    }

    @Override
    protected void handleBundle(Bundle bundle) {
        mAddressInfo = (AddressInfo) bundle.getSerializable("addressInfo");
        mInvoice = bundle.getString("invoice");
        mRemark = bundle.getString("remark");

    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        mTitleText.setText(getResources().getString(R.string.tv_confirm_order));
        setOnClickListener();
        //查询数据库
        mCommPresenter = new CommPresenter(TaskProvider.provideTasksRepository(this), this);
        mCommPresenter.getShoppingCartDataLocal();
        // 创建订单
        new ConfirmOrderPresenter(TaskProvider.provideTasksRepository(this), this);
        mIgnoreList = new ArrayList<>();
        mProRecycle.setLoadingMoreEnabled(false);
        mProRecycle.setPullRefreshEnabled(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.titile_left_imageview:
                finish();
                break;
            case R.id.rb_onlinepay:  //微信支付
            case R.id.rl_onlinepay:
                if (mCheckedPayWay == 3 && mRbOnline.isChecked()) {
                    return;
                }
                mCheckedPayWay = 3;
                mRbOnline.setChecked(true);
                mRgCash.clearCheck();
                mRgCard.clearCheck();
                break;
            case R.id.rb_cashpay: //现金支付
            case R.id.rl_cashpay:
                if (mCheckedPayWay == 1 && mRbCash.isChecked()) {
                    return;
                }
                mCheckedPayWay = 1;
                mRbCash.setChecked(true);
                mRgOnline.clearCheck();
                mRgCard.clearCheck();
                break;
            case R.id.rb_cardpay: //刷卡支付
            case R.id.rl_cardpay:
                if (mCheckedPayWay == 2 && mRbCard.isChecked()) {
                    return;
                }
                mCheckedPayWay = 2;
                mRbCard.setChecked(true);
                mRgOnline.clearCheck();
                mRgCash.clearCheck();
                break;
            case R.id.tv_confirm_order:
                mPresenter.start();  //确认订单
                break;

        }
    }

    public void setOnClickListener() {
        mLeftImg.setOnClickListener(this);
        mRbOnline.setOnClickListener(this);
        mRbCash.setOnClickListener(this);
        mRbCard.setOnClickListener(this);
        mRlOnlinePay.setOnClickListener(this);
        mRlCashPay.setOnClickListener(this);
        mRlCardPay.setOnClickListener(this);
        mConfirmOrder.setOnClickListener(this);
    }


    /**
     * 获取本地购物车数据 并请求结算接口
     *
     * @param info
     */
    @Subscribe
    public void onEventInfo(List<EventShoppingCartInfo> info) {
        mShoppingCartInfo = info;
        mCommPresenter.getShoppingCartDataNet();
    }

    /**
     * 结算接口返回有用数据
     *
     * @param shoppingCartData
     */
    @Override
    public void getShoppingCartDataNetSuc(ApiShoppingCartInfo shoppingCartData) {
        mOrderDeliver.setText(String.format(getString(R.string.moneySymbol), shoppingCartData.deliveryAmount));
        mTotalPrice.setText(String.format(getString(R.string.moneySymbol), shoppingCartData.goodsAmount + shoppingCartData.deliveryAmount));
        mTotalCount.setText(String.format(getString(R.string.goods_count1), shoppingCartData.goodsCount));
        mProRecycle.setLayoutManager(new LinearLayoutManager(this));

        mBaseAdapter = new BaseRecyclerViewAdapter<ApiShoppingCartInfo.ItemsBean>(this, R.layout.item_confirm_pro, shoppingCartData.items, mProRecycle) {

            @Override
            public void updateUI(BaseHolder holder, int position, ApiShoppingCartInfo.ItemsBean data) {
                TextView proName = holder.getView(R.id.proName);
                TextView proCount = holder.getView(R.id.proCount);
                TextView proPrice = holder.getView(R.id.proPrice);
                LinearLayout proLL = holder.getView(R.id.ll_pro);
                if (data.valid) {
                    proLL.setBackgroundColor(getResources().getColor(R.color.white));
                } else {
                    proLL.setBackgroundColor(getResources().getColor(R.color.merchant_line));
                }
                proName.setText(data.name);
                proCount.setText(String.format(mContext.getString(R.string.x), String.valueOf(data.count)));
                proPrice.setText(String.format(mContext.getString(R.string.moneySymbol), data.price));
            }
        };
        mProRecycle.setAdapter(mBaseAdapter);
    }

    /**
     * 店铺ID
     *
     * @return
     */
    @Override
    public String getShopId() {
        return mAddressInfo.shopId;
    }

    /**
     * 支付方式
     *
     * @return
     */
    @Override
    public String getPayWay() {
        return String.valueOf(mCheckedPayWay);
    }

    /**
     * 发票抬头
     *
     * @return
     */
    @Override
    public String getInvoice() {
        return mInvoice;
    }

    /**
     * 备注信息
     *
     * @return
     */
    @Override
    public String getRemark() {
        return mRemark;
    }

    /**
     * 收货地址
     *
     * @return
     */
    @Override
    public ApiHistoryAddressInfo.AddressInfo getAddressInfo() {
        return mAddressInfo;
    }

    /**
     * 本地购物车数据
     *
     * @return
     */
    @Override
    public List<EventShoppingCartInfo> getEventShoppingCartDatas() {
        return mShoppingCartInfo;
    }

    @Override
    public List<String> getIgnoreList() {
        return mIgnoreList;
    }

    @Override
    public void getNeedConfirm(final String needConfirm, String msg) {

        showDialogTwoBtn(msg, "暂不下单", "继续下单", new ICallBack.TwoCallBack() {
            @Override
            public void left(CommDialog dialog) {
                mIgnoreList.clear();
                dialog.dismiss();
            }

            @Override
            public void right(CommDialog dialog) {
                mIgnoreList.add(needConfirm);
                mPresenter.start();  //确认订单
                dialog.dismiss();
            }
        });

    }

    /**
     * 订单返回信息
     * 开始调用支付
     *
     * @param info
     */
    @Override
    public void getApiInfo(ApiConfirmOrderInfo info) {
        // 创建订单成功之后清除数据库
        DBUtils.deleteAll(DBShoppingCartInfo.class);
        EventBus.getDefault().post(info);
        mOrderNo = info.orderNo;
        if (mCheckedPayWay == 3) {   //微信支付
            mWXPayPresenter = new WXPayPresenter(TaskProvider.provideTasksRepository(this), this);
            mWXPayPresenter.loadData();

        } else if (mCheckedPayWay == 1 || mCheckedPayWay == 2) {   // 现金支付，刷卡支付
            Bundle bundle = new Bundle();
            bundle.putString("orderNumber", mOrderNo);
            intentJump(OrderDetailActivity.class, bundle);
        }
    }

    @Override
    public void toast(String msg) {
        ToastUtil.show(msg, Toast.LENGTH_SHORT);
    }

    /**
     * 订单ID
     *
     * @return
     */
    @Override
    public String getOrderNumber() {
        return mOrderNo;
    }

    @Override
    public void refreshInfo() {

    }


}
